let wordsData = []; // 存储所有单词数据
let currentIndex = 0; // 当前显示的单词索引
// 修改获取单词数据的部分，添加bookId参数
let currentBookId = null;

// 从URL获取bookId参数
function getBookIdFromUrl() {
    const params = new URLSearchParams(window.location.search);
    return params.get('bookId');
}

// 加载对应bookId的单词（新增统一加载方法）
async function loadWords() {
    try {
        currentBookId = getBookIdFromUrl();
        if (!currentBookId) {
            window.location.href = '/home.html'; // 无bookId跳回首页
            return;
        }

        // 仅执行带bookId的请求
        const response = await fetch(`/api/words?bookId=${currentBookId}`, {
            credentials: 'include'
        });

        if (!response.ok) throw new Error('接口请求失败');
        const data = await response.json();
        wordsData = data;
        currentIndex = 0; // 重置索引，确保显示第一页
        renderWord(currentIndex);
    } catch (err) {
        console.error('获取单词数据失败：', err);
        document.getElementById('wordContent').innerText = '数据加载失败，请刷新页面';
    }
}


// 渲染指定索引的单词
function renderWord(index) {
    if (index < 0 || index >= wordsData.length) return;

    const word = wordsData[index];
    console.log('当前单词完整数据：', word); // 检查是否有id
    document.getElementById('wordTitle').innerText = `单词：${word.headWord}`;

    let contentHtml = '';
    try {
        const content = word.content; // 直接使用后端返回的对象

        // 1. 音标部分
        const phoneticHtml = `
      <div class="word-info-item">
        <p><strong>美式音标：</strong>${content.usphone || '无'}</p>
        <p><strong>英式音标：</strong>${content.ukphone || '无'}</p>
      </div>
    `;

        // 2. 翻译部分
        const transHtml = `
      <div class="word-info-item">
        <h3>翻译</h3>
        ${content.trans?.map(t => `
          <p>${t.pos}：${t.tranCn}（${t.descOther || '英释'}：${t.tranOther || '无'}）</p>
        `).join('') || '无'}
      </div>
    `;

        // 3. 短语部分
        const phraseHtml = `
      <div class="word-info-item">
        <h3>短语</h3>
        ${content.phrase?.phrases?.map(p => `
          <p>${p.pContent} - ${p.pCn}</p>
        `).join('') || '无'}
      </div>
    `;

        // 4. 例句部分
        const sentenceHtml = `
      <div class="word-info-item">
        <h3>例句</h3>
        <ul>
          ${content.sentence?.sentences?.map(s => `
            <li>${s.sContent} - ${s.sCn}</li>
          `).join('') || '无'}
        </ul>
      </div>
    `;

        // 5. 同根词部分
        const relWordHtml = `
      <div class="word-info-item">
        <h3>同根词</h3>
        ${content.relWord?.rels?.map(r => `
          <p>${r.pos}：${r.words?.map(w => `${w.hwd} - ${w.tran}`).join('、') || '无'}</p>
        `).join('') || '无'}
      </div>
    `;

        // 整合所有部分
        contentHtml = `
      <div class="word-info">
        <p><strong>词频：</strong>${word.wordRank || '未知'}</p>
        <p><strong>所属书籍：</strong>${word.bookId || '未知'}</p>
      </div>
      ${phoneticHtml}
      ${transHtml}
      ${phraseHtml}
      ${sentenceHtml}
      ${relWordHtml}
    `;
    } catch (err) {
        console.error('处理单词内容失败：', err);
        contentHtml = `<p>解析失败：${err.message}</p>`;
    }

    document.getElementById('wordContent').innerHTML = contentHtml;
    document.getElementById('prevBtn').disabled = index === 0;
    document.getElementById('nextBtn').disabled = index === wordsData.length - 1;
}
// 绑定“上一个”按钮事件
document.getElementById('prevBtn').addEventListener('click', () => {
    currentIndex--;
    renderWord(currentIndex);
});

// 绑定“下一个”按钮事件
document.getElementById('nextBtn').addEventListener('click', () => {
    currentIndex++;
    renderWord(currentIndex);
});

let startX = 0;
const wordItem = document.getElementById('wordItem');

// 触摸开始时记录起始位置
wordItem.addEventListener('touchstart', (e) => {
    startX = e.touches[0].clientX;
});

// 触摸结束时判断滑动方向
wordItem.addEventListener('touchend', (e) => {
    const endX = e.changedTouches[0].clientX;
    const diffX = endX - startX;

    if (diffX > 50) {
        // 左滑 → 上一个单词
        if (currentIndex > 0) {
            currentIndex--;
            renderWord(currentIndex);
        }
    } else if (diffX < -50) {
        // 右滑 → 下一个单词
        if (currentIndex < wordsData.length - 1) {
            currentIndex++;
            renderWord(currentIndex);
        }
    }
});

// 绑定“已经记住”按钮事件
document.getElementById('rememberBtn').addEventListener('click', async () => {
    if (!wordsData || wordsData.length === 0) return;

    const currentWord = wordsData[currentIndex];
    if (!currentWord.id) {
        console.error('单词ID不存在，当前单词数据：', currentWord);
        alert('单词ID不存在，请检查数据库结构');
        return;
    }

    try {
        // 1. 获取当前登录用户的ID（需后端接口支持）
        const userRes = await fetch('/api/user', { credentials: 'include' });
        const userData = await userRes.json();
        if (!userData.id) {
            alert('请先登录');
            return;
        }

        // 2. 发送请求记录“已掌握”状态
        const recordRes = await fetch('/api/record-learned', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                userId: userData.id,
                wordId: currentWord.id,   // 需确保world表有`id`字段（主键）
                bookId: currentWord.bookId,
                status: 1 // 1=已掌握
            }),
            credentials: 'include'
        });

        const result = await recordRes.json();
        if (result.success) {
            alert('已标记为“已掌握”！');
        } else {
            alert('标记失败：' + result.message);
        }
    } catch (err) {
        console.error('标记“已经记住”失败：', err);
        alert('网络错误，请重试');
    }
});

window.onload = async function() {
    // 先检查登录状态（如果需要）
    try {
        const userRes = await fetch('/api/user', { credentials: 'include' });
        if (!userRes.ok) {
            window.location.href = '/login.html';
            return;
        }
        // 登录成功后加载对应单词书的单词
        await loadWords();
    } catch (err) {
        window.location.href = '/login.html';
    }
};